﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using System;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;

namespace DNA.Mvc
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class InstallationCheckerAttribute : FilterAttribute, IAuthorizationFilter
    {
        public IDataContext DataContext
        {
            get
            {
                return DependencyResolver.Current.GetService<IDataContext>();
            }
        }

        protected virtual void OnChecked(AuthorizationContext context)
        {
            string controllerName = context.RouteData.Values["controller"] as string;
            if (!string.IsNullOrEmpty(controllerName) && controllerName.Equals("install", StringComparison.OrdinalIgnoreCase)) return;

            if (DnaConfig.IsNeedInstallCheck)
            {
                try
                {
                    //Seems not installed start to checked.
                    //1.Check membership, if membership is null must be not installed.
                    var roles = Roles.GetAllRoles();
                    if (roles.Length > 0)
                    {
                        if (roles.Contains("administrators") && roles.Contains("guests"))
                        {
                            //2.Check dna core database
                            if (DataContext != null)
                            {
                                var home = DataContext.Webs.GetByName("home");

                                if (home != null)
                                {
                                    DnaConfig.SaveDomain(context.HttpContext);
                                    return;
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    HandleInstallation(context);
                }
                HandleInstallation(context);
            }
        }

        private static void HandleInstallation(AuthorizationContext context)
        {
            context.Result = new RedirectToRouteResult("Default", new System.Web.Routing.RouteValueDictionary(new
            {
                controller = "Install",
                action = "Index",
                Area = ""
            }));
        }

        void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext)
        {
            this.OnChecked(filterContext);
        }
    }
}
